package com.gnerv.pabu.basic.core.service.impl;

import com.gnerv.pabu.basic.core.entity.DingDingText;
import com.gnerv.pabu.basic.core.entity.Webhook;
import com.gnerv.pabu.basic.core.service.IDingDingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class DingDingServiceImpl implements IDingDingService {

    @Autowired
    RestTemplate restTemplate;

    @Override
    public boolean sendTextMsg(Webhook webhook, DingDingText dingDingText) {
        String url = webhook.getUrl();
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("contentType", "application/json; charset=utf-8");
        dingDingText.setMsgtype("text");
        dingDingText.getText().setContent(webhook.getKeyWord() + dingDingText.getText().getContent());

        HttpEntity requestEntity = new HttpEntity<>(dingDingText, requestHeaders);
        ResponseEntity<Object> exchange = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Object.class);
        if (exchange.getStatusCodeValue() != 200) {
            log.info("钉钉报警失败！{},errInfo:{}", dingDingText, exchange.getBody());
        }
        return true;
    }

}
